package org.example.utils;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 包名：org.example.utils
 * 用户：admin
 * 日期：2025-09-12
 * 项目名称：pro-demo
 */
@Component
public class HuaweiOBSUtils {

    String url="";
    String ak = System.getenv("ACCESS_KEY_ID");
    String sk = System.getenv("SECRET_ACCESS_KEY_ID");
    String endPoint = "https://obs.cn-north-4.myhuaweicloud.com";
    String bucketName = "web-lwz";
    public String upload(MultipartFile file) throws Exception {

        //得到上传的文件流并得到随机文件名
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        ObsClient obsClient = new ObsClient(ak, sk,endPoint);

        try {
            // 文件上传
            obsClient.putObject(bucketName, fileName, inputStream);
            url = endPoint.split("//")[0] + "//" + bucketName + "." + endPoint.split("//")[1] + "/" + fileName;

//             下面是从本地上传文件的方法
//            PutObjectRequest request = new PutObjectRequest();
//            request.setBucketName("web-lwz");
//            request.setObjectKey(fileName);
//            request.setFile(new File("D:\\图片\\PersonalPhoto\\账号\\github账号.png"));
//            obsClient.putObject(request);

            System.out.println("putObject successfully");
        } catch (ObsException e) {
            System.out.println("putObject failed");
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
        }finally {
            return url;
        }
    }
}
